package com.sci.service.impl;

import com.sci.dto.OrderDTO;
import com.sci.dto.OrderRowDTO;
import com.sci.entity.*;
import com.sci.feign.BusinessServiceClient;
import com.sci.feign.UserServiceClient;
import com.sci.mapper.OrderMapper;
import com.sci.mapper.OrderRowMapper;
import com.sci.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderRowMapper orderRowMapper;


    @Resource
    private BusinessServiceClient businessServiceClient;

    @Resource
    private UserServiceClient userServiceClient;

    // OrderServiceImpl.java
    @Override
    public List<OrderDTO> getOrderDTObyWechatId(String wechatId) {
        try {
            User user = userServiceClient.getUserByWechatId(wechatId);
            if (user == null || user.getWechatId() == null) {
                // 用户服务降级时，尝试通过其他方式获取订单（如直接查询订单表）
                List<Orders> ordersList = orderMapper.selectByWechatId(wechatId);
                return buildDegradedOrderDTOs(ordersList, true, false)
                        .stream()
                        .sorted((o1, o2) -> Integer.compare(o1.getOrders().getStatus(), o2.getOrders().getStatus()))
                        .collect(Collectors.toList());
            }

            List<Orders> ordersList = orderMapper.selectByWechatId(user.getWechatId());
            return buildOrderDTOs(ordersList)
                    .stream()
                    .sorted((o1, o2) -> Integer.compare(o1.getOrders().getStatus(), o2.getOrders().getStatus()))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            // 全局异常处理，返回降级数据
            return buildDegradedOrderDTOs(Collections.emptyList(), true, true)
                    .stream()
                    .sorted((o1, o2) -> Integer.compare(o1.getOrders().getStatus(), o2.getOrders().getStatus()))
                    .collect(Collectors.toList());
        }
    }

    private List<OrderDTO> buildOrderDTOs(List<Orders> ordersList) {
        List<OrderDTO> orderDTOList = new ArrayList<>();
        for (Orders order : ordersList) {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setOrders(order);

            // 商家信息获取（已通过Fallback处理）
            Business business = businessServiceClient.getBusinessById(order.getBusinessId());
            orderDTO.setBusiness(business);
            if (business.getBusinessId().equals("DEFAULT_BUSINESS_ID")) {
                orderDTO.setBusinessServiceDegraded(true);
            }

            List<OrderRowDTO> orderRowDTOs = new ArrayList<>();
            double totalPrice = 0.0;
            List<OrderRow> orderRows = orderRowMapper.selectByOrderId(order.getOrderId());
            for (OrderRow row : orderRows) {
                OrderRowDTO rowDTO = new OrderRowDTO();
                Food food = businessServiceClient.getFoodById(row.getFoodId());
                rowDTO.setFoodName(food.getFoodName());
                rowDTO.setRowPrice(row.getQuantity() * food.getPrice());
                rowDTO.setQuantity(row.getQuantity());

                if (food.getFoodName().equals("商品信息获取失败")) {
                    rowDTO.setFoodServiceDegraded(true);
                    rowDTO.setRowPrice(0.0); // 确保价格为0
                } else {
                    totalPrice += rowDTO.getRowPrice();
                }

                orderRowDTOs.add(rowDTO);
            }
            orderDTO.setOrderRows(orderRowDTOs);
            orderDTO.setTotalPrice(totalPrice);
            orderDTOList.add(orderDTO);
        }
        return orderDTOList;
    }

    private List<OrderDTO> buildDegradedOrderDTOs(List<Orders> ordersList, boolean userDegraded, boolean businessDegraded) {
        return ordersList.stream().map(order -> {
            OrderDTO dto = new OrderDTO();
            dto.setOrders(order);
            dto.setUserServiceDegraded(userDegraded);
            dto.setBusinessServiceDegraded(businessDegraded);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Boolean createOrder(Orders order, List<OrderRow> orderRows) {
        // 插入订单
        orderMapper.insertOrder(order);
        // 批量插入订单行
        if (!orderRows.isEmpty()) {
            orderRowMapper.batchInsert(orderRows);
        }
        return true;
    }


}
